package com.ykt.mall.ctrl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.jfinal.aop.Before;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StringKit;
import com.jfinal.token.TokenManager;
import com.ykt.mall.content.Content;
import com.ykt.mall.interceptor.LoginInterceptor;
import com.ykt.mall.interceptor.SubMitInterceptor;
import com.ykt.model.Customer;
import com.ykt.model.CustomerAddress;
import com.ykt.model.Order;
import com.ykt.model.OrderDetail;
import com.ykt.model.Postage;
import com.ykt.model.Product;
import com.ykt.model.Shop;

@ControllerBind(controllerKey="/submitOrders")//viewPath="/template"
public class SubmitOrderCtrl extends BaseWebController<Postage> {
	@Before(SubMitInterceptor.class)
	public void view(){
		
		int shopId = getParaToInt();
		
		String params = getAttr("sumArrayArea"); //先从attr里面取 如果没有就从页面参数取
		if(params==null) params=getPara("sumArrayArea");
		System.out.println("-params--------->"+params);
		Customer loginCustomer = getLoginCustomer();
		//7,2|6,1
		List<Object> list = new ArrayList<Object>();
		float subTotal = 0.0f;
		if(StringKit.notBlank(params)){
			String[] paramArray = params.split("\\|");
			for(String temp : paramArray){
				if(StringKit.notBlank(temp)){
					String[] tempArray = temp.split(",");
					Map<String,Object> map = new HashMap<String,Object>();
					Product proPo = Product.dao.findById(Integer.valueOf(tempArray[0]));
					float total = proPo.getBigDecimal("now_price").floatValue()*Integer.valueOf(tempArray[1]);
					map.put("proPo", proPo);
					map.put("product_num", tempArray[1]);
					map.put("product_total", total);
					list.add(map);
					subTotal += total;
				}
			}
		}
		//System.out.println("---------->"+subTotal);
		CustomerAddress addr = CustomerAddress.dao.findFirstByCustomerId(loginCustomer.getInt("id"));
		setAttr("addr",addr);
		
		
		int sessionShopId = shopId;
		if(getSessionAttr(Content.SESSION_SHOP) != null){
			Shop sessionShop = getSessionAttr(Content.SESSION_SHOP);
			sessionShopId = sessionShop.getInt("id");
		}
		setAttr("postageList",Postage.dao.findPostageByShopId(sessionShopId));
		
		setAttr("shopPo", Shop.dao.findById(shopId));
		setAttr("productList", list);
		setAttr("subTotal", subTotal);
		
		setAttr("productParams", params);
		
		TokenManager.createToken(this, tokenName, tokenTout);
		setAttr(tokenName, getSessionAttr(tokenName));
		//render("/template/submit_order.html");
		
	}
	
	public void submit(){
		Long tokenl=this.getParaToLong("token");
		int isDelivery = this.getParaToInt("isDelivery");//是否要配送发票
		String delivery_Time = getPara("deliveryTime");//取得配送时间
		Date deliveryTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			deliveryTime = sdf.parse(delivery_Time);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		System.out.println(isDelivery + "==============" + delivery_Time + "======" + deliveryTime);
		
		if(tokenl!=null){
			if(!TokenManager.validateToken(this, tokenName)){
				renderJson("Msg", "请勿重复提交");
				return;
			}
		}
		
		Date date=new Date();
		
		String productParam = this.getPara("productParam");
//		System.out.println("-productParam--------->"+productParam);
//		int shopId = this.getParaToInt("shopId");
//		int addressid = this.getParaToInt("addressid");
//		String remark = this.getPara("remark");
//		String postageName = this.getPara("postageName");
//		String postage = this.getPara("postage");
//		int payment = this.getParaToInt("payment");
//		
//		String gdsTotal = this.getPara("postage");//商品总额
//		String frontMoney = this.getPara("frontMoney");//定金
//		String allTotal = this.getPara("allTotal");//总费用
		//new SimpleDateFormat(format)
		
		Customer loginCustomer = getLoginCustomer();
		
		Long time = System.currentTimeMillis();
		String order_no = String.valueOf(time);
		Map<String,Object> map = new HashMap<String,Object>();
		try{

			Order order = getModel(Order.class);
			order.set("create_time", date);
			order.set("update_time",date);
			order.set("order_no", order_no);
			order.set("customer_id",loginCustomer.getInt("id"));
			order.set("status",0);
			order.set("delivery_time",deliveryTime);
			order.set("need_bill",isDelivery);

			order.save();

			if(StringKit.notBlank(productParam)){

				int orderId = order.getInt("id");

				String[] paramArray = productParam.split("\\|");
				for(String temp : paramArray){
					if(StringKit.notBlank(temp)){
						String[] tempArray = temp.split(",");
						int productId = Integer.valueOf(tempArray[0]);
						int productNum = Integer.valueOf(tempArray[1]);

						Product proPo = Product.dao.findById(productId);
						float productPrice = proPo.getBigDecimal("now_price").floatValue() * productNum;

						OrderDetail od = new OrderDetail();
						od.set("product_id", productId);
						od.set("order_id", orderId);
						od.set("order_id", orderId);
						od.set("product_num",productNum);
						od.set("product_price",productPrice);
						od.set("create_time", date);
						od.set("update_time",date);

						od.save();
					}
				}
			}

			map.put("orderPo", order);
			map.put("Msg", "Ok");
		}catch(Exception e){
			e.printStackTrace();
			map.put("Msg", "提交失败，请重新提交");
		}

		renderJson(map);
	}
	@Before(LoginInterceptor.class)
	public void getAddressList(){
		Customer loginCustomer = getLoginCustomer();
		renderJson(CustomerAddress.dao.findByCustomerId(loginCustomer.getInt("id")));
		
	}
	
	
	
}
